package com.oromwin.repos.common;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

public class Logger {
    static {
        try {
            init();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Logger() {
    }

    private static void init() throws IOException {
        try {
            System.getProperties().load(new FileInputStream(Common.DEFAULT_PROPERTIES));
            PropertyConfigurator.configure(System.getProperties());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Log getLog(Class<?> clazz) {
        return LogFactory.getLog(clazz);
    }

    public static void errorWithThrowable(Log log, String info) {
        errorWithThrowable(log, null, info);
    }
    
    public static void errorWithThrowable(Log log, Throwable th, String info) {
        if (log.isDebugEnabled()) th.printStackTrace();

        if (th == null && log.isErrorEnabled()) 
            log.error("[UNKNOWN] " + info);

        Throwable e = th;
        if (e instanceof RuntimeException && e.getCause() != null)
            e = e.getCause();

        StackTraceElement[] ste = e.getStackTrace();
        if (ste != null && ste.length > 0) {
            String temp = "(" + ste[0].getFileName() + ":" + ste[0].getLineNumber() + ") ";
            info = temp + info;
        }

        if (e.getMessage() != null)
            info = "\"" + e.getMessage() + "\" " + info;

        if (log.isErrorEnabled()) log.error("[ExceptionLog: " + e.getClass().getSimpleName() + "] " + info);
    }
}
